package chapter_08

import scala.io.Source


object chapter_08 {

  def processFile(filename: String, width: Int): Unit = {
    // 8.2 本地函数
    /*
    本地函数不能被外部访问，但是它却可以访问外面
     */
    def processLine(line: String): Unit = {
      if (line.length > width)
        print(filename + ": " + line)
    }

    val source = Source.fromFile(filename)
    for (line <- source.getLines)
      processLine(line)
  }

  def parameter(): Unit = {
    // 参数推断
    val func = (_: Int) + (_: Int)
    println(func(10, 20))
  }

  def parameter2(): Unit = {
    // 8.6 部分应用函数
    def sum(a: Int, b: Int, c: Int) = a + b + c
    def onlyPrint(): Unit = println("Only print")

    println(sum(1, 2, 3))

    val a = sum _ // val a = sum 是不对的
    println(a(1, 2, 3))

    val b = sum(1, _: Int, 3)
    println(b(2))

    val c = onlyPrint _ // 即使没有参数，也不能省略“_”
    c()
  }

  def closureFunc(): Unit = {
    // 8.7 闭包
    var more = 1
    val addMore = (x: Int) => x + more
    println(addMore(10))

    def makeIncreaser(more2: Int) = (x: Int) => x + more2
    val inc1 = makeIncreaser(1)
    val inc9999 = makeIncreaser(9999)
    println(inc1(10))
    println(inc9999(10))
  }

  def parameter3(): Unit = {
    // 8.8 重复参数
    def echo(args: String*) =
      args.foreach(println)

    val arr = Array("What's", "up", "doc?")
    echo(arr: _*) // 不可以这样调用：echo(arr)
  }

  def tailRecursive(): Unit = {
    // 尾递归
    def nestedFun(x: Int): Int = {
      if (x == 0)
        x
      else {
        println(x)
        nestedFun(x - 1)
      }
    }
    nestedFun(10)
  }

  def main(args: Array[String]): Unit = {
//    parameter()
//    parameter2()
//    closureFunc()
//    parameter3()
    tailRecursive()
  }
}
